﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Web;
using Autofac.Integration.Web.Mvc;
using Vowei.Core.Models;
using Vowei.Data;
using Vowei.Data.Models;
using Vowei.Web.Models;

namespace Vowei.Web
{
    public class MvcApplication : System.Web.HttpApplication// , IContainerProviderAccessor
    {
        static IContainerProvider _containerProvider;

        public static IContainerProvider ContainerProviderStatic
        {
            get { return _containerProvider; }
            set { _containerProvider = value; }
        }

        public IContainerProvider ContainerProvider
        {
            get { return _containerProvider; }
        }

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
        }

        protected void Application_Start()
        {
            Database.DefaultConnectionFactory = new SqlConnectionFactory("System.Data.SqlClient");
            Database.SetInitializer<VoweiContextImpl>(new VoweiContextInitializer());
            AreaRegistration.RegisterAllAreas();

            InitIoc();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext ctx = HttpContext.Current;
            string path = ctx.Request.Url.AbsolutePath;

            if (path.IndexOf("_vti_bin") >= 0)
            {
                string newUrl = ctx.Request.ApplicationPath +
                   "TicketService.asmx";
                ctx.RewritePath(newUrl);
            }
        }

        public static void InitIoc()
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<User>().As<IUser>().CacheInSession();
            builder.RegisterType<VoweiContext>().AsImplementedInterfaces();
            builder.RegisterType<VoweiContextImpl>();

            var container = builder.Build();
            _containerProvider = new ContainerProvider(container);
            ControllerBuilder.Current.SetControllerFactory(new AutofacControllerFactory(_containerProvider));
        }
    }
}